/*
 * Copyright (c) 2020-2020, org.smartboot. All rights reserved.
 * project name: smart-license
 * file name: LicenseServer.java
 * Date: 2020-03-22
 * Author: sandao (zhengjunweimail@163.com)
 */

package org.smartboot.license.server;


import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smartboot.license.client.common.Constant;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Calendar;
import java.util.Date;

/**
 * @author 三刀
 * @version V1.0 , 2020/3/20
 */
public class LicenseServer {
    private static final Logger LOGGER = LoggerFactory.getLogger(LicenseServer.class);
    private static final int MAX_DATA_LENGTH = 64;
    private final String sourceFile = "source.txt";
    private final String licenseFile = "license.txt";

    public static void main(String[] args) throws Exception {
        if (args == null || args.length < 2) {
            LOGGER.info("args is invalid");
            return;
        }
        LicenseServer license = new LicenseServer();
        String expire = args[0];
        char type = expire.charAt(expire.length() - 1);
        int value = Integer.valueOf(expire.substring(0, expire.length() - 1));
        Calendar calendar = Calendar.getInstance();
        switch (type) {
            case 'h':
            case 'H':
                calendar.add(Calendar.HOUR, value);
                break;
            case 'd':
            case 'D':
                calendar.add(Calendar.DAY_OF_YEAR, value);
                break;
            case 'y':
            case 'Y':
                calendar.add(Calendar.YEAR, value);
                break;
            default:
                throw new UnsupportedOperationException(expire);
        }
        String data = args[1];
        File file = new File(args[1]);
        if (file.isFile()) {
            LOGGER.info("sign for file:{}", file.getPath());
            data = IOUtils.toString(new FileInputStream(file), StandardCharsets.UTF_8);
        } else {
            LOGGER.info("sign for string:{}", data);
        }
        license.createLicense(data, calendar.getTime());
    }

    /**
     * 生成License
     *
     * @param license    license内容
     * @param expireDate 过期时间
     * @return
     * @throws Exception
     */
    public void createLicense(String license, Date expireDate) throws Exception {
        if (expireDate == null) {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.YEAR, 100);
            calendar.getTime();
            expireDate = new Date();
        }
        //初始化密钥
        //生成密钥对
        KeyPair keyPair = RasUtil.initKey();

        SimpleDateFormat sdf = new SimpleDateFormat(Constant.DATE_FORMAT);
        SourceLicense sourceLicense = new SourceLicense(sdf.format(new Date()), sdf.format(expireDate), license);
        sourceLicense.setPrivateKey(Base64.getEncoder().encodeToString(RasUtil.getPrivateKey(keyPair)));
        sourceLicense.setPublicKey(Base64.getEncoder().encodeToString(RasUtil.getPublicKey(keyPair)));

        createLicense(sourceLicense, keyPair);

        createSourceLicense(sourceLicense);
        LOGGER.info("License data :{}", sourceLicense.getOriginal());
        LOGGER.info("Expire Date:{}", sourceLicense.getExpireDate());
    }

    private void createLicense(SourceLicense sourceLicense, KeyPair keyPair) throws Exception {
        final byte[] privateKey = RasUtil.getPrivateKey(keyPair);
        final Base64.Encoder base64 = Base64.getEncoder();
        //生成License
        File file = new File(licenseFile);
        FileWriter fileWriter = null;
        BufferedWriter bufferedWriter = null;
        try {
            fileWriter = new FileWriter(file);
            bufferedWriter = new BufferedWriter(fileWriter);

            //第一行:公钥
            bufferedWriter.write(base64.encodeToString(RasUtil.getPublicKey(keyPair)));
            bufferedWriter.newLine();
            //第二行:效期
            bufferedWriter.write(base64.encodeToString(
                    RasUtil.encryptByPrivateKey((sourceLicense.getApplyDate() + Constant.DATE_SPLIT + sourceLicense.getExpireDate()).getBytes(), privateKey)));
            bufferedWriter.newLine();

            //密文
            StringBuilder stringBuilder = new StringBuilder();
            byte[] dataBytes = sourceLicense.getOriginal().getBytes();
            int offset = 0;
            int step = dataBytes.length > MAX_DATA_LENGTH ? MAX_DATA_LENGTH : dataBytes.length;
            while (offset < dataBytes.length) {
                stringBuilder.append(base64.encodeToString(RasUtil.encryptByPrivateKey(dataBytes, privateKey, offset, step)));
                stringBuilder.append(System.lineSeparator());
                offset += step;
                step = dataBytes.length - offset > MAX_DATA_LENGTH ? MAX_DATA_LENGTH : dataBytes.length - offset;
            }
            sourceLicense.setEncrypt(stringBuilder.toString());
            bufferedWriter.write(sourceLicense.getEncrypt());

        } finally {
            if (bufferedWriter != null) {
                bufferedWriter.close();
            }
            if (fileWriter != null) {
                fileWriter.close();
            }
        }
    }

    public void createSourceLicense(SourceLicense sourceLicense) throws IOException {
        //生成License
        File file = new File(sourceFile);
        FileWriter fileWriter = null;
        BufferedWriter bufferedWriter = null;
        try {
            fileWriter = new FileWriter(file);
            bufferedWriter = new BufferedWriter(fileWriter);
            bufferedWriter.write("applyDate=" + sourceLicense.getApplyDate());
            bufferedWriter.newLine();
            bufferedWriter.write("expireDate=" + sourceLicense.getExpireDate());
            bufferedWriter.newLine();
            bufferedWriter.write("original=" + sourceLicense.getOriginal());
            bufferedWriter.newLine();
            bufferedWriter.write("encrypt=" + sourceLicense.getEncrypt());
            bufferedWriter.newLine();
            bufferedWriter.write("publicKey=" + sourceLicense.getPublicKey());
            bufferedWriter.newLine();
            bufferedWriter.write("privateKey=" + sourceLicense.getPrivateKey());
        } finally {
            if (bufferedWriter != null) {
                bufferedWriter.close();
            }
            if (fileWriter != null) {
                fileWriter.close();
            }
        }
    }

    /**
     * ASE128秘钥
     *
     * @return
     */
    private byte[] createSecretKey() {
        int length = 16;
        String pre = "license:";
        String end = String.valueOf(System.nanoTime());

        String secretKey = pre + end.substring(end.length() + pre.length() - length);
        LOGGER.info("create secretKey:{}", secretKey);
        return secretKey.getBytes();
    }
}
